<script setup lang="ts">
import { ref, computed } from 'vue'
import { doGetStoreInfoByShopAssistantPhone, doGetStoreTransactionSummaryByStoreId } from '@/apis/home'
import { useUserStore } from '@/store/modules/user'
import QIcon from '@/components/q-icon/q-icon.vue'
import { useStoreInfoStore } from '@/store/modules/storeInfo'
// #ifdef H5  
import ScanPop from '@/components/scan-pop/scan-pop.vue'
// #endif
import { onLoad, onShow ,onPullDownRefresh} from '@dcloudio/uni-app'
import Auth from '@/components/auth/auth.vue'
import useConvert from '@/composables/useConvert'
import { doPutOrderVerification } from '@/apis/order'
import type { DoGetStoreInfoByShopAssistantPhoneResponse } from '@/apis/home/model'
import { doPostLogout } from '@/apis/sign/index'
import {checkCoupon} from '@/apis/home/index'
import qNav from '@/components/q-nav/q-nav.vue'

onLoad(() => {
  uni.$emit('updateTitle')
})

const icons = {
  storeManagement: 'https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20230323/af5ae4debf97480f944aa15e28841319.png',
  theOrderManagement: 'https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20230323/d1b5915381a4424cbbe7be8f1686c276.png',
  fication: 'https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20230323/dec9f0f0613241a0bb54683c24f068b7.png',
  theVerificationCode: 'https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20230323/6bd64447d89d41df94974bfb5685810c.png',
}
const $useUserStore = useUserStore()
const $useConvert = useConvert()
const $useStoreInfoStore = useStoreInfoStore()
const shopAssistantPhone = computed(() => $useUserStore.shopAssistantPhone)
const showOut = ref(false)
const TransactionSummary = ref({
  todayTotalAmount: 0,
  todayTransactionCount: 0,
  todayAverageTransactionValue: 0,
  monthTotalAmount: 0,
  monthTransactionCount: 0,
  monthAverageTransactionValue: 0,
})
const storeInfo = ref<DoGetStoreInfoByShopAssistantPhoneResponse>({
  id: '',
  shopId: '',
  shopName: '',
  storeName: '',
  storeImg: '',
  storeLogo: '',
  status: 'NORMAL',
  functionaryName: '',
  functionaryPhone: '',
  businessStartTime: '',
  businessEndTime: '',
  location: {
    type: 'Point',
    coordinates: [],
  },
  detailedAddress: '',
  startDeliveryDay: 0,
  endDeliveryDay: 0,
})

onShow(() => {
  if (!$useUserStore.token) {
    // uni.reLaunch({ url: '/pages/sign/Index' })
	return
  }
})

onPullDownRefresh(()=>{
	initStoreInfo()
	uni.stopPullDownRefresh();
})
initStoreInfo()

async function initStoreInfo() {
  if (!$useUserStore.token) return
   // uni.reLaunch({ url: '/pages/sign/Index' })
  const { code, data, msg } = await doGetStoreInfoByShopAssistantPhone(shopAssistantPhone.value)
  if (code !== 200) return uni.$msg(msg ? msg : '门店详情获取失败')
  storeInfo.value = data
  $useStoreInfoStore.SET_STORE_INFO(data)
  getStoreTransactionSummary()
}
async function getStoreTransactionSummary() {
  const { code, data } = await doGetStoreTransactionSummaryByStoreId(storeInfo.value.id)
  if (code !== 200) return uni.$msg('门店汇总获取失败')
  TransactionSummary.value = data
}
const handleNavToManage = () => {
	if (!$useUserStore.token) {
		uni.reLaunch({ url: '/pages/sign/Index' })
		return
	}
  if (!$useStoreInfoStore.shopStoreInfo.shopId) return
  uni.navigateTo({ url: '/pages/manage/Index' })
}
const handleOut = () => {
  showOut.value = false
  $useUserStore.REMOVE_TOKEN()
  $useStoreInfoStore.REMOVE_STORE_INFO()
  uni.reLaunch({ url: '/pages/sign/Index' })
  doPostLogout()
}
const handleNavToOrder = () => {
	if (!$useUserStore.token) {
		uni.reLaunch({ url: '/pages/sign/Index' })
		return
	}
  uni.navigateTo({ url: '/pages/order/order' })
}
const handleNavToVerification = () => {
	if (!$useUserStore.token) {
		uni.reLaunch({ url: '/pages/sign/Index' })
		return
	}
  uni.navigateTo({ url: '/pages/writeOffCode/Index' })
}
const showScan = ref(false)

/**
 * 扫码
 */
const handleScan = () => {
 if (!$useUserStore.token) {
 	uni.reLaunch({ url: '/pages/sign/Index' })
 	return
 }
  // #ifdef H5
  showScan.value = true
  // #endif
  // #ifndef H5
  uni.scanCode({
    onlyFromCamera: true,
    success: async function (res) {
		// let result = res.result
		// checkCouponData(result).then(flag=>{
		// 	if(flag){
		// 		if(!result){
		// 			uni.showToast({
		// 			  icon: 'none',
		// 			  title: '优惠券码解析失败',
		// 			})
		// 			return
		// 		}
		// 		uni.navigateTo({
		// 			url:`/subPages/pages/couponRedemption/index?id=${result}`
		// 		})
		// 	}else{
		// 		 bindCode(res.result)
		// 	}
		// })
		bindCode(res.result)
    },
  })
  // #endif
}
 function checkCouponData(id){
	return new Promise( async(resolve, reject)=>{
		const {code} = await checkCoupon(id)
		if(code != 200){
			resolve(false);
		}
		resolve(true);
	})
	
}
async function bindCode(result: string) {
  try {
    const { code, msg } = await doPutOrderVerification({ code: result, storeId: $useStoreInfoStore.storeId })
    if (code && code === 200) {
      uni.showToast({
        icon: 'none',
        title: '核销成功',
      })
    } else {
      uni.showToast({
        icon: 'none',
        title: msg,
      })
    }
  } catch (error) {
    uni.showToast({
      icon: 'none',
      title: '核销失败,请重试',
    })
  }
}
/**
 * H5扫码解析回调
 */
// #ifdef H5
const handleScanResult = async (e: string) => {
  showScan.value = false
  bindCode(e)
}
// #endif
const handlePreviewImg = (storeLogo: string) => {
  uni.previewImage({
    urls: [storeLogo],
  })
}
</script>

<template>
<!-- #ifndef H5  -->
  <q-nav :showBack="false" bgColor="#3d8bf1" title="元圈门店端" color="#ffffff"></q-nav>
  <!-- #endif -->
  <view class="home">
    <view class="home__bg">
      <view class="home__head">
        <view class="home__head-info">
          <view class="home__head-info--img" style="border-radius: 50%; overflow: hidden">
            <image style="width: 100%; height: 100%" :src="storeInfo.storeLogo" @click="handlePreviewImg(storeInfo.storeLogo)" />
          </view>
          <view class="home__head-info--name">
            <view> {{ storeInfo.storeName }}</view>
            <view> {{ shopAssistantPhone }}</view>
          </view>
        </view>
        <view class="home__head-cancel" v-if="$useUserStore.token">
          <!-- <q-icon name="icon-shanghuguanli" color="#fff" size="25px" @click="showOut = true"> </q-icon> -->
		  <image style="width: 50rpx; height: 50rpx" src="~@/assets/img/gerenzhongxin.png" @click="showOut = true" />
        </view>
      </view>
      <view class="home__data">
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ TransactionSummary.todayTransactionCount }}</view
          ><view>今日订单</view>
        </view>
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ $useConvert.divTenThousand(TransactionSummary.todayTotalAmount) }}</view
          ><view>今日交易额</view>
        </view>
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ $useConvert.divTenThousand(TransactionSummary.todayAverageTransactionValue).toFixed(2) }}</view
          ><view>今日客单价</view>
        </view>
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ TransactionSummary.monthTransactionCount }}</view
          ><view>本月订单</view>
        </view>
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ $useConvert.divTenThousand(TransactionSummary.monthTotalAmount) }}</view
          ><view>本月交易额</view>
        </view>
        <view class="home__data-item"
          ><view class="home__data-item--num">{{ $useConvert.divTenThousand(TransactionSummary.monthAverageTransactionValue).toFixed(2) }}</view
          ><view>本月客单价</view>
        </view>
      </view>
    </view>
    <view class="home__tool">
      <view class="home__tool-top">常用工具</view>
      <view class="home__tool-content">
        <view class="home__tool-content--item" @click="handleNavToManage">
          <view class="home__tool-content--icon">
            <image style="width: 100%; height: 100%" :src="icons.storeManagement"></image>
          </view>
          <view>门店管理</view>
        </view>
        <view class="home__tool-content--item" @click="handleNavToOrder">
          <view class="home__tool-content--icon"> <image style="width: 100%; height: 100%" :src="icons.theOrderManagement"></image></view>
          <view>订单管理</view>
        </view>
        <view class="home__tool-content--item" @click="handleScan">
          <view class="home__tool-content--icon"> <image style="width: 100%; height: 100%" :src="icons.fication"></image></view>
          <view>验证核销</view>
        </view>
        <view class="home__tool-content--item" @click="handleNavToVerification">
          <view class="home__tool-content--icon"> <image style="width: 100%; height: 100%" :src="icons.theVerificationCode"></image></view>
          <view>核销码</view>
        </view>
      </view>
    </view>
    <view style="font-size: 24rpx; margin-top: 42rpx; line-height: 40rpx; padding: 20px">
      <view style="font-weight: bold">到店自提说明</view>
      <view>1、备货完成：请您先订单管理中点击【备货完成】，系统才能通知客户到店自提</view>
      <view>2、核销：请客户出示订单中的核销码，请您使用【扫码核销】 或 输入【核销码】进行订单核销操作，核销完成则订单发货成功。 </view>
    </view>
  </view>
  <u-modal v-model="showOut" content="需要退出登录？" show-cancel-button @cancel="showOut = false" @confirm="handleOut"></u-modal>
  <!-- 扫码弹窗 -->
  <!-- #ifdef H5  -->
  <ScanPop v-model="showScan" @analysis-result="handleScanResult" />
  <!-- #endif -->
  <!-- <auth></auth> -->
</template>

<style lang="scss" scoped>
page {
  background: #f9f9f9;
}
@include b(home) {
  @include e(head) {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  @include e(bg) {
    padding-top: 30rpx;
    background: linear-gradient(180deg, #3d8bf1 0%, #f9f9f9 100%);
    padding-bottom: 54rpx;
  }
  @include e(head-info) {
    display: flex;
    align-items: center;
    // flex-shrink: 0;
    @include m(img) {
      width: 80rpx;
      height: 80rpx;
      margin-right: 20rpx;
      margin-left: 30rpx;
      flex-shrink: 0;
    }
    @include m(name) {
      font-size: 32rpx;
      color: #fff;
      // line-height: 80rpx;
    }
  }
  @include e(head-cancel) {
    margin-right: 16rpx;
  }
  @include e(data) {
    border: 1px solid #fff;
    border-radius: 30rpx;
    color: #fff;
    font-size: 24rpx;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    width: 716rpx;
    height: 324rpx;
    margin: 0 auto;
    margin-top: 34rpx;
  }
  @include e(data-item) {
    width: 200rpx;
    text-align: center;
    @include m(num) {
      font-size: 40rpx;
      padding-top: 32rpx;
      margin-bottom: 20rpx;
    }
  }
  @include e(tool) {
    background: #fff;
    width: 716rpx;
    height: 324rpx;
    margin: 0 auto;
    border-radius: 30rpx;
    padding: 36rpx 0 0 34rpx;
  }
  @include e(tool-top) {
    font-size: 16px;
    font-weight: bold;
  }
  @include e(tool-content) {
    display: flex;
    justify-content: space-around;
    margin-top: 56rpx;
    @include m(item) {
      @include flex;
      flex-direction: column;
    }
    @include m(icon) {
      width: 25px;
      height: 25px;
      margin-bottom: 10px;
    }
  }
}
</style>
